import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

// https://react.docschina.org/tutorial/tutorial.html#making-an-interactive-component
class Square extends React.Component {
  render() {
    return (
      <button 
        className="square"
        onClick={() => this.props.onClick()}
      >
        {this.props.value}
      </button>
    )
  }

  state = {value: 'O'}

  toggle = () => {
    const val = String.fromCharCode('O'.charCodeAt() + 'X'.charCodeAt() - this.state.value.charCodeAt())
    this.setState({value: val})
    // console.log(this)
  }
}
class Board extends React.Component { 

  state = {squares: Array(9).fill(null)}

  render() {
    const status = 'Next player: X';

    return (
      <div>
        <div className="status">{status}</div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }

  renderSquare(i) {
    return (
      <Square 
        value={this.state.squares[i]}
        onClick={() => this.handleClick(i)}
      />
    );
  }

  handleClick(i) {
    let squares = this.state.squares.slice()  // slice() 返回副本 ==> 不可变性
    squares[i] = 'X'
    this.setState({squares: squares})
  }
}

class Game extends React.Component {
  render() {
    return (
      <div className="game">
        <div className="game-board">
          <Board />
        </div>
        <div className="game-info">
          <div>{/* status */}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);
